package org.zpmis.api.business;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.stereotype.Service;
import org.zpmis.common.base.AdminLoginUser;
import org.zpmis.common.base.BaseWebService;
import org.zpmis.common.enums.SequenceEnum;
import org.zpmis.common.exception.BusinessException;
import org.zpmis.common.result.ResultCode;
import org.zpmis.common.utils.StringUtil;
import org.zpmis.domain.contract.model.Contract;
import org.zpmis.domain.contract.service.ContractService;
import org.zpmis.domain.project.enums.ProjectEnum;
import org.zpmis.domain.project.enums.ProjectTaskEnum;
import org.zpmis.domain.project.model.Project;
import org.zpmis.domain.project.model.ProjectTask;
import org.zpmis.domain.project.qo.*;
import org.zpmis.domain.project.service.ProjectService;
import org.zpmis.domain.project.service.ProjectTaskService;
import org.zpmis.domain.project.vo.GetProjectDetailVo;
import org.zpmis.domain.project.vo.GetProjectTaskDetailsVo;
import org.zpmis.domain.project.vo.ProjectListVo;
import org.zpmis.domain.sequence.service.SequenceService;
import org.zpmis.domain.user.model.Employee;
import org.zpmis.domain.user.model.SysUser;
import org.zpmis.domain.user.service.EmployeeService;
import org.zpmis.domain.user.service.SysUserService;
import tk.mybatis.mapper.entity.Condition;
import tk.mybatis.mapper.entity.Example;

import java.math.BigDecimal;
import java.time.Instant;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Created with CodeGenerator
 * Description:
 * @author  Yang
 * Date: 2021-6-2
 * Time: 14:53:29
 */
@Service
@Slf4j
public class ProjectWebService extends BaseWebService {
     @Reference
     private ProjectService projectService;

     @Reference
     private SequenceService sequenceService;

     @Reference
     private ContractService contractService;

     @Reference
     private ProjectTaskService projectTaskService;

     @Reference
     private SysUserService sysUserService;

     @Reference
     private EmployeeService employeeService;
    /**
     * 新增项目信息
     * @param addProjectQo
     */
    public void addProject(AddProjectQo addProjectQo) throws BusinessException,Exception {
        //获取当前登录用户
        AdminLoginUser adminLoginUser = super.getAdminLoginUser();
        if(adminLoginUser == null){
            throw new BusinessException(ResultCode.USER_NOT_LOGIN);
        }
        projectService.save(
            Project.builder()
                    .name(addProjectQo.getName())
                    .code(sequenceService.getSequenceNum(SequenceEnum.PROJECT))
                    .startTime(addProjectQo.getStartTime())
                    .totalTime(StringUtil.isEmpty(addProjectQo.getTotalTime()) ? BigDecimal.ZERO : new BigDecimal(addProjectQo.getTotalTime()).setScale(2))
                    .endTime(addProjectQo.getEndTime())
                    .contractId(addProjectQo.getContractId())
                    .description(addProjectQo.getDescription())
                    .status(addProjectQo.getStatus())
                    .archiveStatus(addProjectQo.getArchiveStatus())
                    .attachment(addProjectQo.getAttachment())
                    .sourceLocation(addProjectQo.getSourceLocation())
                    .createId(adminLoginUser.getId())
                    .createPerson(adminLoginUser.getUserName())
                    .createTime(Instant.now().toEpochMilli())
                    .isDeleted(ProjectEnum.NOT_DELETE.code())
                    .build()
        );
    }

    /**
     * 修改项目信息
     * @param editProjectQo
     */
    public void editProject(EditProjectQo editProjectQo) {

        Long id = editProjectQo.getId();
        Project project = projectService.findById(id);
        if(project == null){
            throw new BusinessException(ResultCode.DATA_NOT_FOUND);
        }
        project.setName(editProjectQo.getName());
        //project.setCode(editProjectQo.getCode());
        project.setStartTime(editProjectQo.getStartTime());
        project.setTotalTime(new BigDecimal(editProjectQo.getTotalTime()).setScale(2));
        project.setEndTime(editProjectQo.getEndTime());
        project.setDescription(editProjectQo.getDescription());
        project.setStatus(editProjectQo.getStatus());
        project.setArchiveStatus(editProjectQo.getArchiveStatus());
        project.setAttachment(editProjectQo.getAttachment());
        project.setSourceLocation(editProjectQo.getSourceLocation());
        projectService.update(project);
    }


    /**
     * 删除未开始的项目
     * @param delProjectQo
     * @throws BusinessException
     * @throws Exception
     */
    public void delProject(DelProjectQo delProjectQo) throws BusinessException,Exception {
        Long id = delProjectQo.getId();
        Project project = projectService.findById(id);
        if(project == null){
            throw new BusinessException(ResultCode.DATA_NOT_FOUND);
        }
        Integer status = project.getStatus();
        //不是未开始的项目不允许删除
        if(ProjectEnum.NOT_AT_STATUS.code() != status){
            throw new BusinessException(ResultCode.NO_PERMISSION);
        }
        projectService.update(
                Project.builder()
                .id(id)
                .isDeleted(ProjectEnum.DELETED.code())
                .build()
        );
    }

    /**
     * 项目列表查询
     * @param projectListQo
     * @return
     */
    public PageInfo projectList(ProjectListQo projectListQo) {
        String name = projectListQo.getName();
        String code = projectListQo.getCode();
        Integer status = projectListQo.getStatus();
        Integer archiveStatus = projectListQo.getArchiveStatus();
        Long startTime = projectListQo.getStartTime();
        Long endTime = projectListQo.getEndTime();

        Condition condition = new Condition(Project.class);
        Example.Criteria criteria = condition.createCriteria();
        criteria.andEqualTo("isDeleted",ProjectEnum.NOT_DELETE.code());
        if(StringUtil.isNotEmpty(name)){
            criteria.andLike("name","%"+name+"%");
        }
        if(StringUtil.isNotEmpty(code)){
            criteria.andLike("code","%"+code+"%");
        }
        if(status != null){
            criteria.andEqualTo("status",status);
        }
        if(archiveStatus != null){
            criteria.andEqualTo("archiveStatus",archiveStatus);
        }
        if(startTime != null && endTime != null){
            criteria.andGreaterThanOrEqualTo("createTime",archiveStatus);
            criteria.andLessThanOrEqualTo("createTime",endTime);
        }
        if(startTime != null && endTime == null){
            criteria.andGreaterThanOrEqualTo("createTime",archiveStatus);
            criteria.andLessThanOrEqualTo("createTime",Instant.now().toEpochMilli());
        }
        if(startTime == null && endTime != null){
            criteria.andLessThanOrEqualTo("createTime",endTime);
        }
        condition.orderBy("createTime").desc();
        PageHelper.startPage(projectListQo.getPageNum(),projectListQo.getPageSize());
        List<Project> projectList = projectService.findByCondition(condition);
        PageInfo pageInfo = new PageInfo(projectList);
        //返回自定义对象
        List<ProjectListVo> resultList = projectList.stream().map(ProjectListVo::new).collect(Collectors.toList());
        pageInfo.setList(resultList);
        return pageInfo;
    }


    public GetProjectDetailVo getProjectDetail(GetProjectDetailQo getProjectDetailQo) throws BusinessException,Exception {
        Long id = getProjectDetailQo.getId();
        Project project = projectService.findById(id);
        if(project == null){
            throw new BusinessException(ResultCode.DATA_NOT_FOUND);
        }
        GetProjectDetailVo projectDetailVo = GetProjectDetailVo.toGetProjectDetailVo(project);
        //根据合同id查询合同编号和合同名称
        if(project.getContractId() != null){
            Contract contract = contractService.findById(project.getContractId());
            if(contract != null){
                projectDetailVo.setContractCode(contract.getCode());
                projectDetailVo.setContractName(contract.getName());
            }
        }
        //根据项目id查询该项目所有任务的被指派人信息
        Condition condition = new Condition(ProjectTask.class);
        Example.Criteria criteria = condition.createCriteria();
        criteria.andEqualTo("isDeleted", ProjectTaskEnum.NOT_DELETE.code());
        criteria.andEqualTo("projectId", id);
        //查询所有任务
        List<ProjectTask> projectTaskList = projectTaskService.findByCondition(condition);
        //查询任务下的所有被指派用户
        Map<Long, List<ProjectTask>> projectTaskMap = projectTaskList.stream().filter(item-> item.getSysUid() != null ).collect(Collectors.groupingBy(ProjectTask::getSysUid));
        Map<Long,String> userList = new HashMap<Long,String>();
        for (Map.Entry<Long, List<ProjectTask>> str : projectTaskMap.entrySet()) {
            for(ProjectTask projectTask : str.getValue()){
                if(projectTask.getSysUid() != null){
//                    SysUser sysUser = sysUserService.findById(projectTask.getSysUid());
//                    userList.put(sysUser.getId(),sysUser.getUserName());

                    //如果存在员工信息 显示员工姓名，否则显示用户名 20210908 gf
                    Employee employee = employeeService.findBy("sysUid", projectTask.getSysUid());
                    if(employee != null){
                        userList.put(projectTask.getSysUid(),employee.getName());
                    }else {
                        SysUser sysUser = sysUserService.findById(projectTask.getSysUid());
                        if (sysUser != null) {
                            userList.put(sysUser.getId(), sysUser.getUserName());
                        }
                    }
                }
            }
        }
        projectDetailVo.setUserList(userList);
        return projectDetailVo;
    }

    public List<GetProjectTaskDetailsVo> getProjectTaskList(GetProjectTaskDetailsQo getProjectTaskDetailsQo) throws BusinessException,Exception {
        Long id = getProjectTaskDetailsQo.getProjectId();
        Project project = projectService.findById(id);
        if(project == null){
            throw new BusinessException(ResultCode.DATA_NOT_FOUND);
        }
        Long userId = getProjectTaskDetailsQo.getUserId();
        String name = getProjectTaskDetailsQo.getName();
        Integer level = getProjectTaskDetailsQo.getLevel();
        Integer type = getProjectTaskDetailsQo.getType();
        Integer status = getProjectTaskDetailsQo.getStatus();
        Long startTime = getProjectTaskDetailsQo.getStartTime();
        Long endTime = getProjectTaskDetailsQo.getEndTime();
        //查询该项目下的所有任务
        Condition condition = new Condition(ProjectTask.class);
        Example.Criteria criteria = condition.createCriteria();
        criteria.andEqualTo("isDeleted",ProjectTaskEnum.NOT_DELETE.code());
        criteria.andEqualTo("projectId",getProjectTaskDetailsQo.getProjectId());
        if(userId != null){
            criteria.andEqualTo("sysUid",userId);
        }
        if(StringUtil.isNotEmpty(name)){
            criteria.andLike("name","%"+name+"%");
        }
        if(level != null){
            criteria.andEqualTo("level",level);
        }
        if(type != null){
            criteria.andEqualTo("type",type);
        }
        if(status != null){
            criteria.andEqualTo("status",status);
        }
        if(startTime != null && endTime != null){
            criteria.andGreaterThanOrEqualTo("createTime",startTime);
            criteria.andLessThanOrEqualTo("createTime",endTime);
        }
        if(startTime != null && endTime == null){
            criteria.andGreaterThanOrEqualTo("createTime",startTime);
            criteria.andLessThanOrEqualTo("createTime",Instant.now().toEpochMilli());
        }
        if(startTime == null && endTime != null){
            criteria.andLessThanOrEqualTo("createTime",endTime);
        }
        condition.orderBy("createTime").desc();
        List<ProjectTask> projectTaskList = projectTaskService.findByCondition(condition);
        //返回自定义对象
        List<GetProjectTaskDetailsVo> projectTaskDetailsVos = projectTaskList.stream().map(GetProjectTaskDetailsVo::new).collect(Collectors.toList());

        //显示指派人名称
        projectTaskDetailsVos.stream().forEach(projectTaskDetailsVo -> {
            if(projectTaskDetailsVo.getSysUid() != null){
                Employee employee = employeeService.findBy("sysUid", projectTaskDetailsVo.getSysUid());
                if(employee != null){
                    projectTaskDetailsVo.setSysUserName(employee.getName());
                }else{
                    SysUser sysUser = sysUserService.findById(projectTaskDetailsVo.getSysUid());
                    if(sysUser != null){
                        projectTaskDetailsVo.setSysUserName(sysUser.getUserName());
                    }
                }
            }
            projectTaskDetailsVo.setProjectName(project.getName());
        });
        return projectTaskDetailsVos;
    }

    /**
     * 获取所有项目列表信息
     * @return
     */
    public List<ProjectListVo> projectAllList() {
        Condition condition = new Condition(Project.class);
        Example.Criteria criteria = condition.createCriteria();
        criteria.andEqualTo("isDeleted",ProjectEnum.NOT_DELETE.code());
        List<Project> projectList = projectService.findByCondition(condition);
        //返回自定义对象
        List<ProjectListVo> resultList = projectList.stream().map(ProjectListVo::new).collect(Collectors.toList());

        return resultList;
    }
}
